﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Net.Mail;
using System.Configuration;

public partial class Checkout : BasePage
{
    protected Asah.SiteWorx.Commerce.ShoppingCart MyShoppingCart
    {
        get
        {
            if (Session["MyCart"] == null)
                Session["MyCart"] = new Asah.SiteWorx.Commerce.ShoppingCart();
            return (Asah.SiteWorx.Commerce.ShoppingCart)Session["MyCart"];
        }
        set
        {
            Session["MyCart"] = value;
        }
    }

    protected Asah.SiteWorx.Commerce.Order MyOrder
    {
        get
        {
            if (Session["MyOrder"] == null)
            {
                Asah.SiteWorx.Commerce.Order order = MyShoppingCart.CreateOrder();

                // fill out shipto with profile fields.
                order.ShipTo.Company = Profile.Company;
                order.ShipTo.FirstName = Profile.FirstName;
                order.ShipTo.LastName = Profile.LastName;
                order.ShipTo.Address1 = Profile.StreetAddress;
                order.ShipTo.City = Profile.City;
                order.ShipTo.State = Profile.State;
                order.ShipTo.Zip = Profile.Zip;
                order.ShipTo.Phone = Profile.Phone;

                // Get membership user.
                MembershipUser user = Membership.GetUser(User.Identity.Name);
                order.ShipTo.Email = user.Email;

                Session["MyOrder"] = order;
            }
            return (Asah.SiteWorx.Commerce.Order)Session["MyOrder"];
        }
        set
        {
            Session["MyOrder"] = value;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            MyOrder = null;
            Session["OrderConfirmId"] = null;
            LoadCheckoutForm();
        }

    }

    private void LoadCheckoutForm()
    {
        if (MyOrder != null)
        {
            gvShoppingCart.DataSource = MyOrder.OrderItems;
            gvShoppingCart.DataBind();

            txtShipToCompany.Text = MyOrder.ShipTo.Company;
            txtShipToFName.Text = MyOrder.ShipTo.FirstName;
            txtShipToLName.Text = MyOrder.ShipTo.LastName;
            txtShipToAddress1.Text = MyOrder.ShipTo.Address1;
            txtShipToAddress2.Text = MyOrder.ShipTo.Address2;
            txtShipToCity.Text = MyOrder.ShipTo.City;
            lstShipToState.SelectedValue = MyOrder.ShipTo.State;
            txtShipToZip.Text = MyOrder.ShipTo.Zip;
            txtShipToEmail.Text = MyOrder.ShipTo.Email;
            txtShipToPhone.Text = MyOrder.ShipTo.Phone;
            lstShippingMethod.SelectedValue = Convert.ToInt32(MyOrder.ShipTo.ShippingMethod).ToString();

            txtBillToCompany.Text = MyOrder.BillTo.Company;
            txtBillToCompany.Enabled = !chkSameAsShipping.Checked;
            txtBillToFName.Text = MyOrder.BillTo.FirstName;
            txtBillToFName.Enabled = !chkSameAsShipping.Checked;
            txtBillToLName.Text = MyOrder.BillTo.LastName;
            txtBillToLName.Enabled = !chkSameAsShipping.Checked;
            txtBillToAddress1.Text = MyOrder.BillTo.Address1;
            txtBillToAddress1.Enabled = !chkSameAsShipping.Checked;
            txtBillToAddress2.Text = MyOrder.BillTo.Address2;
            txtBillToAddress2.Enabled = !chkSameAsShipping.Checked;
            txtBillToCity.Text = MyOrder.BillTo.City;
            txtBillToCity.Enabled = !chkSameAsShipping.Checked;
            lstBillToState.SelectedValue = MyOrder.ShipTo.State;
            lstBillToState.Enabled = !chkSameAsShipping.Checked;
            txtBillToZip.Text = MyOrder.BillTo.Zip;
            txtBillToZip.Enabled = !chkSameAsShipping.Checked;
            txtBillToEmail.Text = MyOrder.BillTo.Email;
            txtBillToEmail.Enabled = !chkSameAsShipping.Checked;
            txtBillToPhone.Text = MyOrder.BillTo.Phone;
            txtBillToPhone.Enabled = !chkSameAsShipping.Checked;


            lblShippingAddressInfo.Text = BuildShippingInfo();
            lblBillingAddressInfo.Text = BuildBillingInfo();

            lblShippingMethod.Text = lstShippingMethod.SelectedItem.Text;

            lstExpirationYear.Items.Clear();
            ListItem item = new ListItem("Year", "");
            lstExpirationYear.Items.Add(item);
            lstExpirationYear.Items.Add(DateTime.Now.Year.ToString());
            int addYear = 1;
            while (addYear < 11)
            {
                lstExpirationYear.Items.Add(DateTime.Now.AddYears(addYear).Year.ToString());
                addYear++;
            }
            

        }
        else
        {
            Response.Redirect("CartDetails.aspx", true);
        }


    }

    private string BuildShippingInfo()
    {
        //Build shipping information string.
        System.Text.StringBuilder addressInfo = new System.Text.StringBuilder();

        if (MyOrder.ShipTo.Company.Length > 0)
            addressInfo.Append(MyOrder.ShipTo.Company + "<br>");

        if (MyOrder.ShipTo.FirstName.Length > 0 && MyOrder.ShipTo.LastName.Length > 0)
            addressInfo.Append(MyOrder.ShipTo.FirstName + " " + MyOrder.ShipTo.LastName + "<br>");

        if (MyOrder.ShipTo.Address1.Length > 0)
            addressInfo.Append(MyOrder.ShipTo.Address1 + "<br>");

        if (MyOrder.ShipTo.Address2.Length > 0)
            addressInfo.Append(MyOrder.ShipTo.Address2 + "<br>");

        if (MyOrder.ShipTo.City.Length > 0 && MyOrder.ShipTo.State.Length > 0 && MyOrder.ShipTo.Zip.Length > 0)
            addressInfo.Append(MyOrder.ShipTo.City + " " + MyOrder.ShipTo.State + ", " + MyOrder.ShipTo.Zip + "<br>");
                
        return addressInfo.ToString();
    }

    private string BuildBillingInfo()
    {
        //Build shipping information string.
        System.Text.StringBuilder addressInfo = new System.Text.StringBuilder();

        if (MyOrder.BillTo.Company.Length > 0)
            addressInfo.Append(MyOrder.BillTo.Company + "<br>");

        if (MyOrder.BillTo.FirstName.Length > 0 && MyOrder.BillTo.LastName.Length > 0)
            addressInfo.Append(MyOrder.BillTo.FirstName + " " + MyOrder.BillTo.LastName + "<br>");

        if (MyOrder.BillTo.Address1.Length > 0)
            addressInfo.Append(MyOrder.BillTo.Address1 + "<br>");

        if (MyOrder.BillTo.Address2.Length > 0)
            addressInfo.Append(MyOrder.BillTo.Address2 + "<br>");

        if (MyOrder.BillTo.City.Length > 0 && MyOrder.BillTo.State.Length > 0 && MyOrder.BillTo.Zip.Length > 0)
            addressInfo.Append(MyOrder.BillTo.City + " " + MyOrder.BillTo.State + ", " + MyOrder.BillTo.Zip + "<br>");

        if (MyOrder.BillTo.Phone.Length > 0)
            addressInfo.Append(MyOrder.BillTo.Phone + "<br>");

        if (MyOrder.BillTo.Email.Length > 0)
            addressInfo.Append(MyOrder.BillTo.Email + "<br>");

        return addressInfo.ToString();
    }

    private void SyncBillToShipTo()
    {
        MyOrder.ShipTo.Company = txtShipToCompany.Text;
        MyOrder.ShipTo.FirstName = txtShipToFName.Text;
        MyOrder.ShipTo.LastName = txtShipToLName.Text;
        MyOrder.ShipTo.Address1 = txtShipToAddress1.Text;
        MyOrder.ShipTo.Address2 = txtShipToAddress2.Text;
        MyOrder.ShipTo.City = txtShipToCity.Text;
        MyOrder.ShipTo.State = lstShipToState.SelectedValue;
        MyOrder.ShipTo.Zip = txtShipToZip.Text;
        MyOrder.ShipTo.Email = txtShipToEmail.Text;
        MyOrder.ShipTo.Phone = txtShipToPhone.Text;
        MyOrder.ShipTo.ShippingMethod = (Asah.SiteWorx.Commerce.ShippingMethod)Convert.ToInt32(lstShippingMethod.SelectedValue);

        if (chkSameAsShipping.Checked)
        {
            MyOrder.BillTo.Company = txtShipToCompany.Text;
            MyOrder.BillTo.FirstName = txtShipToFName.Text;
            MyOrder.BillTo.LastName = txtShipToLName.Text;
            MyOrder.BillTo.Address1 = txtShipToAddress1.Text;
            MyOrder.BillTo.Address2 = txtShipToAddress2.Text;
            MyOrder.BillTo.City = txtShipToCity.Text;
            MyOrder.BillTo.State = lstShipToState.SelectedValue;
            MyOrder.BillTo.Zip = txtShipToZip.Text;
            MyOrder.BillTo.Email = txtShipToEmail.Text;
            MyOrder.BillTo.Phone = txtShipToPhone.Text;
        }
        else
        {
            MyOrder.BillTo.Company = txtBillToCompany.Text;
            MyOrder.BillTo.FirstName = txtBillToFName.Text;
            MyOrder.BillTo.LastName = txtBillToLName.Text;
            MyOrder.BillTo.Address1 = txtBillToAddress1.Text;
            MyOrder.BillTo.Address2 = txtBillToAddress2.Text;
            MyOrder.BillTo.City = txtBillToCity.Text;
            MyOrder.BillTo.State = lstBillToState.SelectedValue;
            MyOrder.BillTo.Zip = txtBillToZip.Text;
            MyOrder.BillTo.Email = txtBillToEmail.Text;
            MyOrder.BillTo.Phone = txtBillToPhone.Text;
        }
        
    }
    protected void wizCheckout_NextButtonClick(object sender, WizardNavigationEventArgs e)
    {
        SyncBillToShipTo();
        LoadCheckoutForm();
    }
    protected void chkSameAsShipping_CheckedChanged(object sender, EventArgs e)
    {
        if (!chkSameAsShipping.Checked)
        {
            MyOrder.BillTo.Company = "";
            MyOrder.BillTo.FirstName = "";
            MyOrder.BillTo.LastName = "";
            MyOrder.BillTo.Address1 = "";
            MyOrder.BillTo.Address2 = "";
            MyOrder.BillTo.City = "";
            MyOrder.BillTo.State = "";
            MyOrder.BillTo.Zip = "";
            MyOrder.BillTo.Email = "";
            MyOrder.BillTo.Phone = "";
        }
        else
        {
            MyOrder.BillTo.Company = MyOrder.ShipTo.Company;
            MyOrder.BillTo.FirstName = MyOrder.ShipTo.FirstName;
            MyOrder.BillTo.LastName = MyOrder.ShipTo.LastName;
            MyOrder.BillTo.Address1 = MyOrder.ShipTo.Address1;
            MyOrder.BillTo.Address2 = MyOrder.ShipTo.Address2;
            MyOrder.BillTo.City = MyOrder.ShipTo.City;
            MyOrder.BillTo.State = MyOrder.ShipTo.State;
            MyOrder.BillTo.Zip = MyOrder.ShipTo.Zip;
            MyOrder.BillTo.Email = MyOrder.ShipTo.Email;
            MyOrder.BillTo.Phone = MyOrder.ShipTo.Phone;
        }
        LoadCheckoutForm();
    }
    protected void lblEditShipping_Click(object sender, EventArgs e)
    {
        wizCheckout.ActiveStepIndex = 0;
        LoadCheckoutForm();
    }
    protected void lnkbtnEditBilling_Click(object sender, EventArgs e)
    {
        wizCheckout.ActiveStepIndex = 1;
        LoadCheckoutForm();
    }
    protected void wizCheckout_FinishButtonClick(object sender, WizardNavigationEventArgs e)
    {
        SubmitOrder();
    }

    private void SubmitOrder()
    {
        if (Page.IsValid)
        {
            SyncBillToShipTo();
            MyOrder.PaymentDetail.NameOnCard = txtNameOnCard.Text;
            MyOrder.PaymentDetail.PaymentMethod = (Asah.SiteWorx.Commerce.PaymentMethod)Convert.ToInt32(lstPaymentMethods.SelectedValue);
            MyOrder.PaymentDetail.CardNumber = txtCardNumber.Text;
            MyOrder.PaymentDetail.ExpirationMonth = lstExpirationMonth.SelectedValue;
            MyOrder.PaymentDetail.ExpirationYear = lstExpirationYear.SelectedValue;

            if (MyOrder.IsValid)
            {
                MyOrder = MyOrder.Save();
                Session["OrderConfirmId"] = MyOrder.ID;

                //Send confirmation email.
                SendEmail(MyOrder.ID);


                MyOrder = null;
                MyShoppingCart = null;
                Response.Redirect("OrderConfirmation.aspx", true);
            }
            else
            {
                CustomValidator validator;
                foreach (Csla.Validation.BrokenRule rule in MyOrder.BrokenRulesCollection)
                {
                    validator = new CustomValidator();
                    validator.ErrorMessage = rule.Description;
                    validator.IsValid = false;
                    Page.Validators.Add(validator);
                }
                foreach (Csla.Validation.BrokenRule rule in MyOrder.ShipTo.BrokenRulesCollection)
                {
                    validator = new CustomValidator();
                    validator.ErrorMessage = rule.Description;
                    validator.IsValid = false;
                    Page.Validators.Add(validator);
                }
                foreach (Csla.Validation.BrokenRule rule in MyOrder.BillTo.BrokenRulesCollection)
                {
                    validator = new CustomValidator();
                    validator.ErrorMessage = rule.Description;
                    validator.IsValid = false;
                    Page.Validators.Add(validator);
                }
                foreach (Csla.Validation.BrokenRule rule in MyOrder.PaymentDetail.BrokenRulesCollection)
                {
                    validator = new CustomValidator();
                    validator.ErrorMessage = rule.Description;
                    validator.IsValid = false;
                    Page.Validators.Add(validator);
                }

            }
        }
    }

    private void SendEmail(int orderNumber)
    {
        // email requester

        string message = "Your order number is " + orderNumber + " and you will be contacted to confirm this order.";

        SmtpClient client = new SmtpClient();
        MailMessage email = new MailMessage();

        // Get membership user.
        MembershipUser user = Membership.GetUser(User.Identity.Name);

        email.To.Add(user.Email);
        email.Subject = "Classic Legacy Order Submitted";
        email.Body = message;

        try
        {
            client.Send(email);
        }
        catch { }

        // email order manager
        string siteUrl = ConfigurationManager.AppSettings["SiteUrl"];
        string salesEmail = ConfigurationManager.AppSettings["SalesEmail"];

        message = "The order <a href=\"" + siteUrl + "/SiteWorx/OrderManagement.aspx?id=" + 
            orderNumber + "\">" + orderNumber + "</a> was submitted for your approval." ;
        email = new MailMessage();

        email.IsBodyHtml = true;
        email.To.Add(salesEmail);
        email.Subject = "New Order Submitted";
        email.Body = message;

        try
        {
            client.Send(email);
        }
        catch { }

    }

    protected void gvShoppingCart_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Footer)
        {
            Label lblGrandTotal = (Label)e.Row.FindControl("lblGrandTotal");
            lblGrandTotal.Text = String.Format("{0:c}", MyOrder.Total);
        }
    }
}
